package com.hyg.lib_music.ui.fragment;

import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.icu.text.SimpleDateFormat;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.hyg.lib_base.Net.NetworkUtils;
import com.hyg.lib_common.Base.BaseApplication;
import com.hyg.lib_common.DataModel.Music.FavMusic;
import com.hyg.lib_common.DataModel.Music.Music;
import com.hyg.lib_common.DataModel.Music.MusicRecommendCheckData;
import com.hyg.lib_common.DataModel.Music.MusicRecommendData;
import com.hyg.lib_common.Net.CommonHttpUtil;
import com.hyg.lib_common.sweetalertdialog.SweetAlertDialog;
import com.hyg.lib_music.R;
import com.hyg.lib_music.adapter.MusicCountViewBinder;
import com.hyg.lib_music.adapter.MusicRecommendHeadViewBinder;
import com.hyg.lib_music.adapter.MusicViewBinder;
import com.hyg.lib_music.modle.HealthCourseInfoData;
import com.hyg.lib_music.presenter.MusicRecommendContract;
import com.hyg.lib_music.presenter.di.components.DaggerActivityComponent;
import com.hyg.lib_music.service.MusicService;
import com.hyg.lib_music.ui.activity.MusicMainActivity;
import com.hyg.lib_music.ui.activity.TesttingTizhiActivity;
import com.hyg.lib_music.ui.activity.TesttingXinliActivity;
import com.hyg.lib_music.ui.activity.TreatmentFinishActivity;
import com.hyg.lib_music.util.ApplicationComponentUtil;
import com.hyg.lib_music.util.MusicChangeEvent;
import com.hyg.lib_music.util.MusicFavManager;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONException;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.ref.WeakReference;
import java.net.URLDecoder;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.inject.Inject;

import me.drakeet.multitype.Items;
import me.drakeet.multitype.MultiTypeAdapter;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

//音乐处方页
public class MusicRecommendFragment extends BaseFragment {
    private ImageView noRecommendLayout;
    private SmartRefreshLayout refreshLayout;
    private MultiTypeAdapter mAdapter;
    private MusicRecommendData musicRecommendData;
    private List<Music> musicList;//总集合，循环用
    public SweetAlertDialog pDialog = null;

    LinearLayout yangsheng_ln, sleep_ln, relax_ln;
    ImageView yangsheng_iv, sleep_iv, relax_iv, result_iv;
    TextView yangshen_tv, sleep_tv, relax_tv, result_tv, tv_total_days, tv_total_minute;

    RecommendJieyaFragment jieyaFragment;
    RecommendShuimianFragment shuimianFragment;
    RecommendYangshengFragment yangshengFragment;

    FragmentManager fragmentManager;
    Fragment currrentFrg;

    private Items items;

    private MusicService.MusicServiceBinder serviceBinder;

    int time_total = 0;
    Handler handler;
    MusicMainActivity musicMainActivity = (MusicMainActivity) getActivity();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_music_main, container, false);
        initView(view);
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        getCourseInfo();
    }

    public void initView(View view) {
        fragmentManager = getChildFragmentManager();
        yangsheng_ln = view.findViewById(R.id.ln_music_yangsheng);
        sleep_ln = view.findViewById(R.id.ln_music_sleep);
        relax_ln = view.findViewById(R.id.ln_music_relax);
        yangsheng_iv = view.findViewById(R.id.iv_music_yangsheng);
        sleep_iv = view.findViewById(R.id.iv_music_sleep);
        relax_iv = view.findViewById(R.id.iv_music_relax);
        yangshen_tv = view.findViewById(R.id.tv_music_yangsheng);
        sleep_tv = view.findViewById(R.id.tv_music_sleep);
        relax_tv = view.findViewById(R.id.tv_music_relax);
        result_iv = view.findViewById(R.id.iv_result);
        result_tv = view.findViewById(R.id.tv_result);
        tv_total_days = view.findViewById(R.id.tv_total_days);
        tv_total_minute = view.findViewById(R.id.tv_total_minute);

        yangsheng_ln.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                changeHealthBtnView(0);
                switchFragment(yangshengFragment);
            }
        });
        sleep_ln.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                changeHealthBtnView(1);
                switchFragment(shuimianFragment);
            }
        });
        relax_ln.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                changeHealthBtnView(2);
                switchFragment(jieyaFragment);
            }
        });
        showMusciRecommend();
//        getCourseInfo();
    }

    public void showMusciRecommend() {
        fragmentManager = getChildFragmentManager();
        yangshengFragment = new RecommendYangshengFragment();
        shuimianFragment = new RecommendShuimianFragment();
        jieyaFragment = new RecommendJieyaFragment();
        switchFragment(yangshengFragment);
    }


    private void switchFragment(Fragment fragment) {
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        if (currrentFrg == null) {
            transaction.add(R.id.ln_fragment_container, fragment).commit();
            currrentFrg = fragment;
        } else if (fragment != currrentFrg) {
            if (!fragment.isAdded()) {
                transaction.hide(currrentFrg)
                        .add(R.id.ln_fragment_container, fragment).commit();
            } else {
                transaction.hide(currrentFrg)
                        .show(fragment).commit();
            }
            currrentFrg = fragment;
        }
    }

    @SuppressLint("UseCompatLoadingForDrawables")
    public void changeHealthBtnView(int i) {
        yangsheng_iv.setBackground(null);
        sleep_iv.setBackground(null);
        relax_iv.setBackground(null);
        yangshen_tv.setTextColor(getResources().getColor(R.color.musicTextBlack));
        sleep_tv.setTextColor(getResources().getColor(R.color.musicTextBlack));
        relax_tv.setTextColor(getResources().getColor(R.color.musicTextBlack));
        switch (i) {
            case 0:
                yangsheng_iv.setBackground(getResources().getDrawable(R.drawable.circlular_voilet_light_solid));
                yangshen_tv.setTextColor(getResources().getColor(R.color.mainMusicColor));
                break;
            case 1:
                sleep_iv.setBackground(getResources().getDrawable(R.drawable.circlular_voilet_light_solid));
                sleep_tv.setTextColor(getResources().getColor(R.color.mainMusicColor));
                break;
            case 2:
                relax_iv.setBackground(getResources().getDrawable(R.drawable.circlular_voilet_light_solid));
                relax_tv.setTextColor(getResources().getColor(R.color.mainMusicColor));
                break;
        }
    }

    public void changeCourseData(int id, String result, int days, int uminutes) {
        result_iv.setImageResource(id);
        result_tv.setText(result);
        tv_total_days.setText(days + "");
        tv_total_minute.setText(uminutes + "");
    }


    public final mainHandler mHandler = new mainHandler(this);

    private class mainHandler extends Handler {
        private final WeakReference<MusicRecommendFragment> mFragment;

        public mainHandler(MusicRecommendFragment fragment) {
            mFragment = new WeakReference<MusicRecommendFragment>(fragment);
        }

        @Override
        public void handleMessage(Message msg) {
            MusicRecommendFragment fragment = mFragment.get();
            if (msg.what == 1) {
                Log.i("lgb", "handleMessage: 1");
                fragment.time_total++;
                fragment.tv_total_minute.setText(fragment.time_total + "");
                updataMusicTimes(fragment.getActivity());
                sendEmptyMessageDelayed(1, 60000);
            }
        }
    }

    public void getCourseInfo() {
        CommonHttpUtil.getMusicCourceInfo(getActivity(), 1, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                Log.i("lgb", "onResponse:resultsss222= " + result);
                HealthCourseInfoData data = JSONObject.parseObject(result, HealthCourseInfoData.class);
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (data.code == 200) {
                            updateTopView(data);
                            if (data.data.status == 3) {
                                startActivity(new Intent(getActivity(), TreatmentFinishActivity.class));
                            }
                        } else {
                            Log.i("lgb", "run: 查询用户疗程信息失败");
                        }
                    }
                });
            }
        });
    }

    @SuppressLint("NewApi")
    public long getPastDays(String data) {
        long days = 0;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date date = simpleDateFormat.parse(data);
            long titmesss = date.getTime();
            long currenttimes = System.currentTimeMillis();
            days = (currenttimes - titmesss) / (24 * 60 * 60 * 1000);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return days;
    }


    public void updateTopView(HealthCourseInfoData data) {
        MusicRecommendFragment fragment = (MusicRecommendFragment) getParentFragment();
//                            fragment.changeCourseData(data.data.);
        int id = R.mipmap.result_good_icon;
        String result = "愉悦";
        switch (data.data.feeling) {
            case 0:
                id = R.mipmap.result_good_icon;
                result = "愉悦";
                break;
            case 1:
                id = R.mipmap.result_bad_icon;
                result = "低落";
                break;
            case 2:
                id = R.mipmap.result_common_icon;
                result = "一般";
                break;
            case 3:
                id = R.mipmap.result_good_icon;
                result = "愉悦";
                break;
            case 4:
                id = R.mipmap.result_best_icon;
                result = "高涨";
                break;
        }
        time_total = data.data.times;
        changeCourseData(id, result, data.data.days, time_total);
        if (MusicMainActivity.serviceBinder != null && MusicMainActivity.serviceBinder.isPlaying()) {
            Log.i("lgb", "updateTopView:sendEmptyMessage ");
            mHandler.removeCallbacksAndMessages(null);
            mHandler.sendEmptyMessageDelayed(1, 60000);
        }
    }

    public void updataMusicTimes(Context context) {
        CommonHttpUtil.updateCourceTimes(context, 1, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.i("lgb", "updataMusicTimes onResponse: " + response.body().string());
            }
        });
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
        mHandler.removeCallbacksAndMessages(null);
    }

    public void startCount() {
        Log.i("lgb", "startCount: ");
        mHandler.removeCallbacksAndMessages(null);
        mHandler.sendEmptyMessageDelayed(1, 60000);
    }

    public void stopCount() {
        Log.i("lgb", "stopCount: ");
        mHandler.removeCallbacksAndMessages(null);
    }


}